import {
	showToast
} from '../utils.js'

let baseUrl = 'http://localhost:9164/'
// let baseUrl = '/wx_api/'


// 验证token是否过期
const isVerify = (url) => {
	let flag = false;
	if (url != 'user/wxAuthorization' &&  url != 'user/wxLogin' && url != 'user/wxLogout') {
		//判断token是否到期
		let expires_in = uni.getStorageSync('expires_in');
		if (expires_in < new Date().getTime()) { //token过期
			flag = true;
		}
	}
	return flag;
}

//设置刷新后的缓存
const refreshToken = (response) => {
	var timestamp = new Date().getTime() - 10000; //当前时间戳-10秒
	uni.setStorageSync('public_token', response.data.access_token);
	uni.setStorageSync('publicrefresh_token', response.data.refresh_token);
	uni.setStorageSync('expires_in', timestamp + response.data.expires_in);
}

//清空缓存跳转到登录页面
const toLoginPage = () => {
	uni.clearStorageSync();
	uni.reLaunch({ //并关闭其他页面
		url: '/pages/login/login',
	})
}

//请求接口
const getRequest = (url, data, method, contentType) => {
	//开始
	return new Promise((resolve, reject) => {
		let header = {
			"Content-Type": contentType || "application/x-www-form-urlencoded;charset=utf-8",
		}
		if (uni.getStorageSync('publictoken')) {
			header['public_token'] = uni.getStorageSync('publictoken')
		}

		uni.request({
			url: baseUrl + url, //接口地址
			data: {
				...data,
			},
			method: method,
			header: header,
			dataType: 'text',
			responseType: 'text',
			success: (res) => {
				let resData = JSON.parse(res.data)
				resolve(resData);

			},
			fail: (err) => {
				showToast(`网络错误，请稍后重试～`) // request:fail
				err && reject(err)
			}
		});
	})
	//结束
};


const getUpload = (url, data, files) => {
	//请求开始
	return new Promise((resolve, reject) => {
		let header = {}

		if (uni.getStorageSync('publictoken')) {
			header['public_token'] = uni.getStorageSync('publictoken')
		}
		
		uni.uploadFile({
			url: baseUrl + url, //接口地址
			header: header,
			files: files,
			formData: data,
			success: (res) => {
				
				let resData = JSON.parse(res.data)

				if (resData.error_description) {
					showToast(resData.error_description)
					resData && reject(resData) // 返回错误
				} else {
					if ((!resData.error_description || resData.code == '200') && resData.code !=
						'400' && resData.code !=
						'500' &&
						resData.code != '401') {
						resData && resolve(resData) // 返回数据
					} else {
						if (resData.code == '401') {
							showToast('登录超时，请重新登录')
							// uni.reLaunch({
							// 	url: '/pages/login/login'
							// });
						} else {
							showToast(resData.msg || resData.message)
						}
						resData && reject(resData)
					}
				}
			},
			fail: (err) => {
				showToast(`网络错误，请稍后重试～`) // request:fail
				err && reject(err)
			}
		});
	})
	//请求结束

};


export const request = (url, data, method, contentType) => {
	let flag = isVerify(url);
	if (flag) {
		//token过期刷新token
		
		let refresh_token = uni.getStorageSync('publicrefresh_token');
		//请求新token
		let refreshConfig = {
			method: "GET", // 请求方式
			url: baseUrl + 'user/refreshToken',
			data: {
				"publicrefresh_token": refresh_token
			}
		}
		let promise = new Promise(function(resolve, reject) {
			//判断有数据
			if (refresh_token && refresh_token != '') {
				//请求新token
				uni.request(refreshConfig).then(responses => {
					if (responses[0]) {
						reject({
							message: "网络超时"
						});
					} else {
						let response = responses[1].data;
						if (response.code == 1) { //刷新成功
							refreshToken(response); //设置缓存

							getRequest(url, data, method, contentType).then(res => {
								if (res.code == 1) { //请求成功
									resolve(res);
								} else {
									reject({
										message: res.msg
									});
								}
							}).catch(error => {
								reject(error);
							})
						} else {

							toLoginPage();
						}
					}
				})
			}
			// else {
			// 		console.log('进入这里了')
			// 	toLoginPage();

			// }
		})
		return promise;
	} else {
		//token未过期或路径不需检测过期
		return getRequest(url, data, method, contentType)

	}
};

//文件上传
export const uploadFile = (url, data, files) => {
	let flag = isVerify(url);
	if (flag) {
		//token过期刷新token
		let publicrefresh_token = uni.getStorageSync('publicrefresh_token');
		//请求新token
		let refreshConfig = {
			method: "GET", // 请求方式
			url: baseUrl + 'user/refreshToken',
			data: {
				"publicrefresh_token": publicrefresh_token
			}
		}
		
		let promise = new Promise(function(resolve, reject) {
			//判断有数据
			if (publicrefresh_token && publicrefresh_token != '') {
				//请求新token
				uni.request(refreshConfig).then(responses => {
					if (responses[0]) {
						reject({
							message: "网络超时"
						});
					} else {
						let response = responses[1].data;
						if (response.code == 1) { //刷新成功
							refreshToken(response); //设置缓存
							getUpload(url, data, files).then(res => {
								if (res.code == 1) { //请求成功
									resolve(res);
								} else {
									reject({
										message: res.msg
									});
								}
							}).catch(error => {
								reject(error);
							})
						} else {
							toLoginPage();
						}
					}
				})
			} else {
				toLoginPage();
			}
		})
		return promise
	} else {
		return getUpload(url, data, files)

	}
};


//本地模拟
export const imitateGet = (url, data) => {
	return new Promise((resolve, reject) => {
		uni.request({
			url: url, //接口地址
			data: {
				...data,
			},
			method: 'GET',
			dataType: 'text',
			responseType: 'text',
			success: (res) => {

				let resData = JSON.parse(res.data)
				resolve(resData)

			}
		});
	})

}

